import './index.css'
import * as THREE from 'three'
import {
    OrbitControls
} from 'three/examples/jsm/controls/OrbitControls'

/**
 * Geometry
 */
// const geometry = new THREE.PlaneGeometry(1,1);


// const geometry = new THREE.PlaneGeometry(1, 1);
const row = 100; // 200
const column = row;
const count = row * column;
const geometry = new THREE.BufferGeometry();
const positions = new Float32Array(count * 3);
const uvs = new Float32Array(count * 2);
for (let j = 0; j < row; j++) {
  for (let i = 0; i < column; i++) {
    const x = i / column - 0.5; // -0.5-0.5
    const y = j / row - 0.5; // -0.5-0.5
    const u = x + 0.5; // 0-1
    const v = y + 0.5; // 0-1
    positions.set([x, y, 0], (i + j * column) * 3);
    uvs.set([u, v], (i + j * column) * 2);
  }
}
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
geometry.setAttribute("uv", new THREE.BufferAttribute(uvs, 2));


const vertex = `
    varying vec2 vUv;
    void main(){
        vUv = uv;
        vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
        gl_Position = projectionMatrix * mvPosition;
        gl_PointSize = 10.0 / -mvPosition.z;
    }
`

const fragment = `
    uniform sampler2D uTexture;

    varying vec2 vUv;

    void main() {
        // gl_FragColor = vec4(vUv, 0.0, 1.0);
        vec4 color = texture2D(uTexture, vUv);
        gl_FragColor = color;
    }

`

/**
 * Matetrial
 */
import img from '@/assets/img/fadou-white.png'
const material = new THREE.ShaderMaterial({
    vertexShader: vertex,
    fragmentShader: fragment,
    // wireframe: true,
    uniforms: {
        uTime: { value: 0 },
        uTexture: {
        value: new THREE.TextureLoader().load(img),
        },
    },
})

/**
 * Mesh
 */
const mesh = new THREE.Points(geometry, material);

/**
 * Size
 */
const Size = {
    width: window.innerWidth,
    height: window.innerHeight
}


/**
 * Camera
 */
const camera = new THREE.PerspectiveCamera(75, Size.width / Size.height, 0.1, 100)
camera.position.z = 3

/**
 * Scene
 */
const scene = new THREE.Scene()
scene.add(mesh)

/**
 * Renderer
 */
const canvas = document.querySelector('canvas.webgl')
const renderer = new THREE.WebGLRenderer({
    canvas
})
renderer.setSize(Size.width, Size.height)
renderer.setClearColor('#f19191')



/**
 * OrbitControls
 */
// const controls = new OrbitControls(camera, canvas)
// controls.enableDamping = true



/**
 * Update
 */
let clock = new THREE.Clock();
let elpasedTime = 0;
const tick = () => {
    elpasedTime = clock.getElapsedTime();
    material.uniforms.uTime.value = elpasedTime;
    // controls.update();
    renderer.render(scene, camera)
    requestAnimationFrame(tick)
}
tick()